<template>
  <div v-if="show" class="login-modal-overlay" @click.self="closeModal">
    <div class="login-modal">
      <div class="login-modal-header">
        <h2>{{ title }}</h2>
        <button class="close-btn" @click="closeModal">×</button>
      </div>
      
      <div class="login-content">
        <!-- 左侧登录表单 -->
        <div class="login-left">
          <!-- 登录方式切换 -->
          <div class="login-tabs">
            <div 
              class="login-tab" 
              :class="{ active: activeTab === 'password' }"
              @click="activeTab = 'password'"
            >
              密码登录
            </div>
            <div 
              class="login-tab" 
              :class="{ active: activeTab === 'register' }"
              @click="activeTab = 'register'"
            >
              注册
            </div>
          </div>
          
          <!-- 注册表单 -->
          <div v-if="activeTab === 'register'" class="login-form">
            <div class="form-group">
              <input type="text" placeholder="请输入用户名" v-model="userName" class="bordered-input">
            </div>
            <div class="form-group">
              <input type="text" placeholder="请输入账号" v-model="userAccount" class="bordered-input">
            </div>
            <div class="form-group">
              <input type="password" placeholder="请输入密码" v-model="userPassword" class="bordered-input">
            </div>
            <div class="form-group">
              <input type="password" placeholder="请确认密码" v-model="checkPassword" class="bordered-input">
            </div>
            <!-- 错误信息提示 -->
            <div v-if="errorMessage" class="error-message">
              {{ errorMessage }}
            </div>
            <div class="form-actions">
              <button class="login-btn" @click="register" :disabled="isLoading">
                <span v-if="isLoading">注册中...</span>
                <span v-else>注册</span>
              </button>
            </div>
          </div>
          
          <!-- 密码登录表单 -->
          <div v-if="activeTab === 'password'" class="login-form">
            <div class="form-group">
              <input type="text" placeholder="请输入邮箱/手机号（国际号码加区号）" v-model="account" class="bordered-input">
            </div>
            <div class="form-group">
              <div class="password-input">
                <input type="password" placeholder="请输入密码" v-model="password">
                <span class="forgot-password" @click="forgotPassword">忘记密码</span>
              </div>
            </div>
            <!-- 错误信息提示 -->
            <div v-if="errorMessage" class="error-message">
              {{ errorMessage }}
            </div>
            <div class="form-actions">
              <button class="register-btn" @click="activeTab = 'register'">注册</button>
              <button class="login-btn" @click="login">登录</button>
            </div>
          </div>
          
          <!-- 其他登录方式 -->
          <div class="other-login">
            <div class="other-login-text">其它登录：</div>
            <div class="other-login-icons">
              <span class="other-icon weibo">🔄</span>
              <span class="other-icon wechat">💬</span>
              <span class="other-icon github">🐙</span>
            </div>
            <div v-if="activeTab === 'password'" class="switch-login">
              <span @click="activeTab = 'register'">注册账号</span>
            </div>
          </div>
        </div>
        
        <!-- 右侧二维码登录 -->
        <div class="login-right">
          <div class="qr-login">
            <div class="qr-title">扫码登录 <span class="qr-version">(6.4.1及以上版本支持)</span></div>
            <div class="qr-code">
              <div class="qr-image"></div>
              <div class="qr-icon">
                <span class="qr-arrow">↓</span>
              </div>
            </div>
            <div class="qr-tip">
              打开 <span class="app-name">稀土掘金APP</span><br>
              点击"我-左上角扫一扫"登录
            </div>
          </div>
        </div>
      </div>
      
      <!-- 用户协议 -->
      <div class="agreement">
        注册登录即表示同意 <a href="#">用户协议</a> 和 <a href="#">隐私政策</a>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { useUserStore } from '@/stores/user.js'

export default {
  name: 'LoginModal',
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  setup() {
    const userStore = useUserStore()
    return {
      userStore
    }
  },
  data() {
    return {
      title: '登录掘金畅享更多权益',
      activeTab: 'password',
      phone: '',
      verificationCode: '',
      account: '',
      password: '',
      userName: '',
      userAccount: '',
      userPassword: '',
      checkPassword: '',
      errorMessage: '',
      isLoading: false
    }
  },
  methods: {
    closeModal() {
      this.$emit('close')
      // 清除表单数据和错误信息
      this.account = ''
      this.password = ''
      this.phone = ''
      this.verificationCode = ''
      this.userName = ''
      this.userAccount = ''
      this.userPassword = ''
      this.checkPassword = ''
      this.errorMessage = ''
    },
    getVerificationCode() {
      // 获取验证码逻辑
      console.log('获取验证码')
    },
    async login() {
      // 清除之前的错误信息
      this.errorMessage = ''
      
      if (this.activeTab === 'password') {
        // 验证输入
        if (!this.account || !this.password) {
          this.errorMessage = '请输入账号和密码'
          return
        }
        
        this.isLoading = true
        
        try {
          // 调用后端登录接口
          const response = await axios.post('http://localhost:8121/api/user/login', {
            userAccount: this.account,
            userPassword: this.password
          }, {
            withCredentials: true  // 确保发送和接收cookies
          })
          
          // 检查响应
          if (response.data && response.data.code === 0) {
            // 登录成功
            const userData = response.data.data
            
            // 保存token到localStorage（如果后端返回了token）
            if (response.data.token) {
              localStorage.setItem('token', response.data.token)
            } else if (response.headers && response.headers.authorization) {
              localStorage.setItem('token', response.headers.authorization)
            } else {
              // 如果没有token，可能使用session，我们保存用户ID作为标识
              localStorage.setItem('userId', userData.id)
            }
            
            // 设置登录状态并获取完整用户信息
            localStorage.setItem('isLoggedIn', 'true')
            await this.userStore.fetchUserInfo()
            
            console.log('登录成功，用户信息:', this.userStore.userInfo)
            this.$emit('login-success', { 
              nickname: this.userStore.userInfo.nickname,
              avatar: this.userStore.userInfo.userAvatar,
              userId: this.userStore.userInfo.id
            })
            this.closeModal()
          } else {
            // 登录失败
            this.errorMessage = response.data.message || '登录失败，请检查账号密码'
          }
        } catch (error) {
          console.error('登录请求失败:', error)
          if (error.response) {
            // 服务器返回错误响应
            this.errorMessage = error.response.data.message || '登录失败，请检查账号密码'
          } else if (error.request) {
            // 请求发送失败
            this.errorMessage = '网络连接失败，请检查网络或后端服务是否启动'
          } else {
            // 其他错误
            this.errorMessage = '登录失败，请稍后重试'
          }
        } finally {
          this.isLoading = false
        }
      } else {
        // 验证码登录逻辑
        console.log('验证码登录/注册')
        // 这里可以添加验证码登录的逻辑
      }
    },
    async register() {
      // 清除之前的错误信息
      this.errorMessage = ''
      
      // 验证输入
      if (!this.userName || !this.userAccount || !this.userPassword || !this.checkPassword) {
        this.errorMessage = '请填写完整的注册信息'
        return
      }
      
      // 验证密码一致性
      if (this.userPassword !== this.checkPassword) {
        this.errorMessage = '两次输入的密码不一致'
        return
      }
      
      // 验证密码长度
      if (this.userPassword.length < 6) {
        this.errorMessage = '密码长度不能少于6位'
        return
      }
      
      this.isLoading = true
      
      try {
        // 调用后端注册接口
        const response = await axios.post('http://localhost:8121/api/user/register', {
          checkPassword: this.checkPassword,
          userAccount: this.userAccount,
          userName: this.userName,
          userPassword: this.userPassword
        }, {
          withCredentials: true  // 确保发送和接收cookies
        })
        
        // 检查响应
        if (response.data && response.data.code === 0) {
          // 注册成功
          alert('注册成功！请使用密码登录')
          // 切换到密码登录标签页
          this.activeTab = 'password'
          // 清空注册表单
          this.userName = ''
          this.userAccount = ''
          this.userPassword = ''
          this.checkPassword = ''
        } else {
          // 注册失败
          this.errorMessage = response.data.message || '注册失败，请重试'
        }
      } catch (error) {
        console.error('注册请求失败:', error)
        if (error.response) {
          // 服务器返回错误响应
          this.errorMessage = error.response.data.message || '注册失败，请重试'
        } else if (error.request) {
          // 请求发送失败
          this.errorMessage = '网络连接失败，请检查网络或后端服务是否启动'
        } else {
          // 其他错误
          this.errorMessage = '注册失败，请稍后重试'
        }
      } finally {
        this.isLoading = false
      }
    },
    forgotPassword() {
      // 忘记密码逻辑
      console.log('忘记密码')
    }
  }
}
</script>

<style scoped>
.login-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.login-modal {
  background-color: white;
  border-radius: 8px;
  width: 800px;
  max-width: 90%;
  padding: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.login-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.login-content {
  display: flex;
  gap: 40px;
}

.login-left {
  flex: 1;
}

.login-right {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.login-modal-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #1d2129;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #86909c;
}

.login-tabs {
  display: flex;
  border-bottom: 1px solid #e5e6eb;
  margin-bottom: 24px;
}

.login-tab {
  padding: 12px 0;
  margin-right: 24px;
  cursor: pointer;
  font-size: 16px;
  color: #86909c;
  position: relative;
}

.login-tab.active {
  color: #1d2129;
  font-weight: 500;
}

.login-tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 2px;
  background-color: #1e80ff;
}

.login-form {
  margin-bottom: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.phone-input {
  display: flex;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
  overflow: hidden;
}

.country-code {
  display: flex;
  align-items: center;
  padding: 0 12px;
  background-color: #f7f8fa;
  border-right: 1px solid #e5e6eb;
  font-size: 14px;
  color: #1d2129;
}

.dropdown-arrow {
  font-size: 10px;
  margin-left: 4px;
  color: #86909c;
}

input {
  flex: 1;
  padding: 12px;
  border: none;
  outline: none;
  font-size: 14px;
}

.bordered-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
  outline: none;
  font-size: 14px;
  box-sizing: border-box;
}

.verification-input {
  display: flex;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
  overflow: hidden;
}

.verification-btn {
  padding: 0 12px;
  background: none;
  border: none;
  border-left: 1px solid #e5e6eb;
  color: #1e80ff;
  font-size: 14px;
  cursor: pointer;
  white-space: nowrap;
}

.password-input {
  position: relative;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
}

.forgot-password {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #1e80ff;
  font-size: 14px;
  cursor: pointer;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background-color: #1e80ff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 8px;
}

.register-link {
  margin-top: 16px;
  text-align: center;
}

.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 16px;
}

.register-btn {
  background: none;
  color: #1e80ff;
  padding: 4px 20 px;
  border-radius: 4px; 
  cursor: pointer;
  flex: 1;
  width: 50%;
  padding: 12px;
  background-color: #1e80ff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  margin-top: 8px;
}

.form-actions .login-btn {
  flex: 1;
}

.qr-login {
  padding: 24px;
  background-color: #f7f8fa;
  border-radius: 8px;
  text-align: center;
  width: 100%;
}

.qr-title {
  font-size: 16px;
  color: #1d2129;
  margin-bottom: 16px;
}

.qr-version {
  font-size: 12px;
  color: #86909c;
}

.qr-code {
  width: 160px;
  height: 160px;
  margin: 0 auto 16px;
  position: relative;
}

.qr-image {
  width: 100%;
  height: 100%;
  background-color: #e5e6eb;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48px;
  color: #86909c;
}

.qr-image {
  background-image: url('@/assets/login/QR.png');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.qr-image::after {
  content: '';
}

.qr-icon {
  position: absolute;
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
  width: 32px;
  height: 32px;
  background-color: #1e80ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.qr-tip {
  font-size: 14px;
  color: #86909c;
  line-height: 1.6;
}

.app-name {
  color: #1e80ff;
}

.other-login {
  display: flex;
  align-items: center;
  margin-top: 24px;
  flex-wrap: wrap;
  gap: 8px;
}

.other-login-text {
  font-size: 14px;
  color: #86909c;
  margin-right: 12px;
}

.other-login-icons {
  display: flex;
  gap: 16px;
}

.other-icon {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #f7f8fa;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.switch-login {
  margin-left: auto;
  font-size: 14px;
  color: #1e80ff;
  cursor: pointer;
}

.agreement {
  text-align: center;
  font-size: 12px;
  color: #86909c;
  margin-top: 24px;
}

.agreement a {
  color: #1e80ff;
  text-decoration: none;
}

/* 错误信息样式 */
.error-message {
  color: #f56c6c;
  font-size: 14px;
  margin-top: 8px;
  margin-bottom: 8px;
}

/* 用户头像样式 */
.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  cursor: pointer;
  background-size: cover;
  background-position: center;
  position: relative;
}

/* 用户面板样式 */
.user-panel {
  position: absolute;
  top: 50px;
  right: 0;
  width: 300px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 16px;
  z-index: 1000;
}

.user-panel-header {
  display: flex;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e6eb;
}

.user-panel-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 16px;
  background-size: cover;
  background-position: center;
}

.user-panel-info {
  flex: 1;
}

.user-panel-name {
  font-size: 16px;
  font-weight: 500;
  color: #1d2129;
  margin-bottom: 4px;
}

.user-panel-level {
  font-size: 14px;
  color: #86909c;
  display: flex;
  align-items: center;
}

.level-progress {
  height: 4px;
  background-color: #e5e6eb;
  border-radius: 2px;
  margin: 4px 0;
  overflow: hidden;
}

.level-progress-bar {
  height: 100%;
  background-color: #1e80ff;
  width: 50%;
}

.user-panel-stats {
  display: flex;
  justify-content: space-between;
  padding: 16px 0;
  border-bottom: 1px solid #e5e6eb;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 16px;
  font-weight: 500;
  color: #1d2129;
}

.stat-label {
  font-size: 12px;
  color: #86909c;
  margin-top: 4px;
}

.user-panel-menu {
  padding: 16px 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  color: #1d2129;
  font-size: 14px;
  cursor: pointer;
}

.menu-item:hover {
  color: #1e80ff;
}

.menu-icon {
  margin-right: 8px;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-panel-footer {
  display: flex;
  justify-content: space-between;
  padding-top: 16px;
  border-top: 1px solid #e5e6eb;
  font-size: 14px;
}

.settings-link, .logout-link {
  color: #86909c;
  cursor: pointer;
}

.settings-link:hover, .logout-link:hover {
  color: #1e80ff;
}
</style>